package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.pojo.User;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    MenuDao menuDao;
    @Autowired
    UserDao userDao;
    @Autowired
    RoleDao roleDao;

    @Override
    public void add(Menu menu) {
        menuDao.add(menu);
    }

    @Override
    public void del(Integer[] ids) {
        menuDao.delMedium(ids);
        menuDao.del(ids);
    }

    @Override
    public void update(Menu menu) {
        menuDao.update(menu);
    }

    @Override
    public List<Menu> findAll() {
        List<Menu> menus = menuDao.findAll();
        return menus;
    }

    @Override
    public Menu findOne(Menu menu) {
        Menu one = menuDao.findOne(menu);
        return one;
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Menu> menus = menuDao.findPage(queryPageBean.getQueryString());
        return new PageResult(menus.getTotal(), menus.getResult());
    }

    @Override
    public List<Menu> getMenuList(String username) {
        User user = userDao.findByUsername(username);
        List<Integer> roleIds = roleDao.findRoleIdsByUserId(user.getId());
        List<Menu> menuList = new ArrayList<>();
        if (roleIds != null && roleIds.size() > 0) {
            for (Integer roleId : roleIds) {
                List<Integer> menuIds = menuDao.getMenuIDsByRoleId(roleId);
                for (Integer menuId : menuIds) {
                    Menu menu = menuDao.getMenuParent(menuId);
                    if (menu != null) {
                        List<Menu> menus = menuDao.getMenuSon(menu.getId());
                        menu.setChildren(menus);
                        menuList.add(menu);
                    }
                }
            }
        }
        return menuList;
    }
}
